<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\CarRepertoryCalendar;
use app\common\model\Category;

/**
 * 车辆相关接口
 * Class Cars
 * @package app\api\controller
 */
class Cars extends Api
{
    // 车辆（搜索）列表、车辆详情接口，不需要登录可访问
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 车辆分类接口
     */
    public function getCarCategory()
    {
        $category = new Category();
        $_data = $category->getCategoryIdAndName();
        $data = [
            ['label'=>'所有分类','value'=>0]
        ];
        $i=1;
        foreach ($_data as $k=>$v){
            $data[$i]['label'] = $v;
            $data[$i]['value'] = $k;
            $i++;
        }
        $this->success('操作成功', $data);
    }

    /**
     * 车辆列表，包含搜索功能
     * @throws \think\Exception
     */
    public function carList()
    {
        // 开始时间和结束时间
        $startDate = $this->request->request('startDate');
        $endDate = $this->request->request('endDate');
        // 车辆分类
        $categoryId = $this->request->request('categoryId');
        // 价格范围，拖动类型
        $maxPrice = $this->request->request('maxPrice');

        // 价格范围，经济型（0-150），舒适型（150-300），经验型（300以上）
        $priceType = $this->request->request('priceType');
        // 排序类型 0=>默认排序，根据权重排序，1=>价格从低到高，2=>价格从高到低
        $orderType = $this->request->request('orderType');
        //当前页
        $page = $this->request->param('page',1);
        //显示多少条数据
        $rows = $this->request->param('rows',5);

        // 默认条件
        $where = 'switch = 1 and total_inventory > 0';

        if($startDate && $endDate){
            $carRepertoryCalendar = new CarRepertoryCalendar();
            // 如果查到 两个日期之间有库存为0的车辆，在再搜车辆的时候加上条件 not in 车辆id集合
            $carIdList = $carRepertoryCalendar->getCarRepertoryByTime($startDate,$endDate);
            if($carIdList){
                $str =  implode($carIdList,',');
                $where .= " and id not in ($str)";
            }
        }

        // 分类查询
        if($categoryId!=0){
            $category = new Category();
            $categoryIds = $category->getCategoryIds($categoryId);

            // 品牌筛选
            if($categoryIds){
                $categoryId_arr = [$categoryId];
                $categoryId_arr = array_merge($categoryId_arr,$categoryIds);
                $categoryId_str =  implode($categoryId_arr,',');
                $where .= " and category_ids in ($categoryId_str)";
            }else{
                $where .= " and category_ids = $categoryId";
            }
        }

        // 价格范围筛选
        if($maxPrice>0 && $maxPrice <300){
            $where .= " and price < $maxPrice";
        }

        // 价格段位筛选
        if($priceType==1){
            $where .= " and price >= 0 and price < 150";
        }else if($priceType==2){
            $where .= " and price >= 150 and price < 300";
        }else if($priceType==3){
            $where .= " and price > 300";
        }

        // 默认添加时间倒叙，可选价格正序或到序
        if($orderType==1){
            $order = ['price'=>'asc'];
        }else if($orderType==2){
            $order = ['price'=>'desc'];
        }else{
            $order = ['weigh'=>'desc'];
        }
        $cars = new \app\admin\model\Cars();
        $carList = $cars->field('id,category_ids,title,price,flag,json,images')
            ->where($where)
            ->order($order)
            ->page($page,$rows)
            ->select();
//        echo $cars->getLastSql();

        $total = $cars->where($where)->count();
        // 总页码
        $totalPage = (int)ceil($total/$rows);

        $items = [];
        foreach ($carList as $k=>$car){
            $items[$k]['id'] = $car->id;
            $items[$k]['title'] = $car->title;
            $items[$k]['price'] = $car->price;
            // 得到车辆图片
            $server_url = "http://" . $_SERVER['HTTP_HOST'];
            $_arr = explode(',', $car->images);
            $items[$k]['goodsUrl'] = $server_url . $_arr[0];
            // 得到车辆短信息
            $info_str = "";
            if($car->json){
                $info_arr = array_values(json_decode($car->json,true));
                $info_str = implode('/',$info_arr);
            }
            $items[$k]['type'] = $info_str;
            $items[$k]['flag'] = $car->flag_text;
        }

        $data = [
            'total' =>$total,
            'totalPage' => $totalPage,
            'items' => $items
        ];
        $this->success('操作成功',$data);
    }


    /**
     * 车辆详情
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        $carId = $this->request->request('carId');
        $carModel = new \app\admin\model\Cars();
        $car = $carModel::where(['id' => $carId, 'switch' => 1])->field('id,category_ids,title,price,flag,json,images')->find();
        if (!$car) {
            $this->error(__('Data Is Empty'));
        }

        $car = $this->spliceCarDetailInfo($car)->toArray();

        $this->success(__('Operation Success'), $car);
    }

    /**
     * 拼接车辆信息
     * @param $car
     * @return mixed
     */
    private function spliceCarDetailInfo($car){
        // 拼接车辆图片地址
        $server_url = "http://" . $_SERVER['HTTP_HOST'];
        $_arr = explode(',', $car->images);
        foreach ($_arr as $k => $v) {
            $imagesList[$k] = $server_url . $v;
        }
        $car->images = $imagesList;
        // 拼接车辆分类名称
        $categoryModel = new Category();
        $categoryName = $categoryModel->whereIn('id', $car->category_ids, '')->column('name');
        $car->categoryName = $categoryName;
        // 解析json
        $car->json = json_decode($car->json,true);
        return $car;
    }
}
